<template>
  <div>
    <el-upload
        :disabled="disabled"
        action="#"
        :http-request="uploadFileAction"
        :before-upload="handleBeforeUpload"
        :on-exceed="handleExceed"
        :on-success="successUpload"
        :show-file-list="false">
      <el-button :disabled="disabled" type="primary" size="small" :loading="uploadLoading">点击上传</el-button>
    </el-upload>
  </div>

</template>
<script>
import {uploadFile} from "@/api/homeApi";

export default {
  data() {
    return {
      uploadLoading: false,
      fileData: ''
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    supportType: {//支持上传文件的格式
      default: () => ['jpeg', 'supportType', 'png', 'pdf','xls','xlxs','doc','docx','mp4','avi','mov'],
      type: Array
    },
    limit: {
      type: Number,
      default: 1
    },
    fileSize: {
      type: Number,
      default: 100
    }
  },
  methods: {
    uploadFileAction({file, onProgress}) {
      this.uploadLoading = true
      let formData = new FormData()
      formData.append('file', file)
      formData.append('open', true)
      uploadFile(formData, progress => {
        onProgress(progress)
      }).then(res => {
            console.log('上传成功',res)
            if (res.code == 200) {
              this.fileData = res.data
              this.$emit('setFileUrl', this.fileData)
            }else {
              this.$message.error('上传文件失败！')
            }
      }).catch(() => {
        this.$message.error('上传文件失败！')
      }).finally(() => {
        this.uploadLoading = false
      })
    },
    // 这个函数不生效
    successUpload() {
      this.$emit('setFileUrl', this.fileData)
    },
    handleExceed() {
      this.$message.error(`只能上传${this.limit}份文件`)
    },
    handleBeforeUpload(file) {
      const isLt = file.size / 1024 / 1024 < this.fileSize
      // 提取文件后缀名,并将其转换为小写
      const fileExtension = file.name.split('.').pop().toLowerCase();
      if (this.supportType.indexOf(fileExtension) == -1) {
        let supportType = this.supportType
        let msg = supportType.join('、')
        this.$message.error(`请上传正确的文件格式！支持的格式有：${msg}`)
        return false
      }
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过${this.fileSize}MB!`)
        return false
      }
    }
  },
}
</script>
<style scoped>
</style>
